//! 应用上下文模块
//! 
//! 提供应用运行时的上下文信息和管理

use crate::utils::error::{YayaError, Result};

/// 应用上下文
pub struct AppContext {
    pub app_id: usize,
    pub app_name: String,
    pub stack_base: usize,
    pub heap_base: usize,
    pub privileges: AppPrivileges,
}

/// 应用特权级别
#[derive(Debug, Clone)]
pub struct AppPrivileges {
    pub can_access_network: bool,
    pub can_access_filesystem: bool,
    pub can_access_hardware: bool,
    pub can_create_threads: bool,
}

/// 应用上下文管理器
pub struct ContextManager {
    contexts: Vec<AppContext>,
}

impl ContextManager {
    /// 创建新的上下文管理器
    pub fn new() -> Result<Self, YayaError> {
        Ok(ContextManager {
            contexts: Vec::new(),
        })
    }
    
    /// 初始化上下文管理器
    pub fn init() -> Result<(), YayaError> {
        info!("初始化应用上下文管理器");
        Ok(())
    }
    
    /// 关闭上下文管理器
    pub fn shutdown() -> Result<(), YayaError> {
        info!("关闭应用上下文管理器");
        Ok(())
    }
    
    /// 创建应用上下文
    pub fn create_context(&mut self, app_id: usize, app_name: &str, privileges: AppPrivileges) -> Result<usize, YayaError> {
        let context_id = self.contexts.len();
        
        let context = AppContext {
            app_id,
            app_name: app_name.to_string(),
            stack_base: 0x100000 + context_id * 0x10000, // 简化地址分配
            heap_base: 0x200000 + context_id * 0x100000,
            privileges,
        };
        
        self.contexts.push(context);
        info!("创建应用上下文: {} (ID: {})", app_name, app_id);
        
        Ok(context_id)
    }
    
    /// 获取应用上下文
    pub fn get_context(&self, context_id: usize) -> Option<&AppContext> {
        self.contexts.get(context_id)
    }
    
    /// 获取当前活动上下文
    pub fn get_current_context(&self) -> Option<&AppContext> {
        // 简化实现：返回第一个上下文
        self.contexts.first()
    }
}

/// 获取全局上下文管理器实例
pub fn get_context_manager() -> &'static mut ContextManager {
    static mut CONTEXT_MANAGER: Option<ContextManager> = None;
    
    unsafe {
        if CONTEXT_MANAGER.is_none() {
            CONTEXT_MANAGER = Some(ContextManager::new().unwrap());
        }
        CONTEXT_MANAGER.as_mut().unwrap()
    }
}